#ifndef LIGHT_TEMPHUM_WIDGET_H
#define LIGHT_TEMPHUM_WIDGET_H

#include <QtMqtt/QtMqtt>
#include <QtMqtt/QMqttClient>
#include <QWidget>
#include "fsmpLight.h"
#include "fsmpTempHum.h"
#include <QTimer>
#include "ui_light_temphum_widget.h"
#include "config.h"

namespace Ui {
class Light_TempHum_Widget;
}

class Light_TempHum_Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Light_TempHum_Widget(QWidget *parent = nullptr);
    ~Light_TempHum_Widget();

    fsmpLight *light;

    fsmpTempHum *th;

    QTimer *timer;


    void onlineService()
    {
        //        client = new QMqttClient;
        //        //绑定连接成功信号
        //        connect(client,&QMqttClient::connected,this, &Light_TempHum_Widget::connectSuccess);
        //        connect(client,&QMqttClient::disconnected,this, &Light_TempHum_Widget::connectError);
        //        //绑定连接的ip
        //        client->setHostname(MQTT_HOSTNAME);
        //        //绑定端口
        //        client->setPort(MQTT_PORT);
        //        //连接服务器
        //        client->connectToHost();
        if(client != nullptr)
        {
            qDebug()<< "Is Connected";
        }
        else
        {
            qDebug()<< "Error unConnected";
        }
    }

    void localService()
    {
        //定时器
        timer = new QTimer(this);
        connect(timer,SIGNAL(timeout()),this,SLOT(getMessage()));
        timer->start(1000);
    }

    void publishLightMsg(double sum, int id)
    {
        QString lightmsg = QString::asprintf(LIGHT,sum,id);
        client->publish(QString(MQTT_DEVICE_SIM),lightmsg.toLatin1().data());
        //qDebug() << lightmsg;
    }

    void publishTem_HumMsg(double tem, double hub, int id)
    {
        QString tem_hummsg = QString::asprintf(TEM_HUM, tem, hub, id);
        client->publish(QString(MQTT_DEVICE_SIM),tem_hummsg.toLatin1().data());
        //qDebug() << tem_hummsg;
    }



private:
    Ui::Light_TempHum_Widget *ui;
    double lightValue;
    double temValue;
    double humValue;
private slots:
    void connectSuccess()
    {
        qDebug() << "connect sucess";
    }
    void connectError()
    {
        qDebug() << "connect error";
    }
    void getMessage()
    {
        lightValue = light->getValue();
        temValue = th->temperature();
        humValue = th->humidity();
        //获取光照强度
        ui->lineEdit_light->setText(QString::number(lightValue));
        //获取温度
        ui->lineEdit_temp->setText(QString::number(temValue));
        //获取湿度
        ui->lineEdit_hum->setText(QString::number(humValue));
        publishLightMsg(lightValue,0);
        publishTem_HumMsg(temValue,humValue,0);
    }
    void on_backButton_clicked();
};


#endif // LIGHT_TEMPHUM_WIDGET_H
